package com.tcm.day01;

/**
 * 排序
 */
public class Code02_selectSort {

    /**
     * 选择排序
     *
     * @param arr
     */
    public static void selectSort(int[] arr) {
        int N = arr.length;
        for (int i = 0; i < N; i++) {
            int minIdx = i;
            for (int j = i + 1; j < N; j++) {
                minIdx = arr[minIdx] < arr[j] ? minIdx : j;
            }
            swap(arr, minIdx, i);
        }
    }

    /**
     * 冒泡排序
     *
     * @param arr
     */
    public static void bubbleSort(int[] arr) {
        int N = arr.length;
        for (int i = 0; i < N - 1; i++) {
            for (int j = 0; j < N - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) swap(arr, j, j + 1);
            }
        }
    }

    /**
     * 插入排序
     *
     * @param arr
     */
    public static void insertSort1(int[] arr) {
        int N = arr.length;
        for (int end = 1; end < N; end++) {
            int minIdx = end;
            while (minIdx - 1 >= 0 && arr[minIdx - 1] > arr[minIdx]) {
                swap(arr, minIdx - 1, minIdx);
                minIdx--;
            }
        }
    }

    public static void insertSort2(int[] arr) {
        int N = arr.length;
        for (int end = 1; end < N; end++) {
            for (int prev = end - 1; prev >= 0 && arr[prev] > arr[prev + 1]; prev--) {
                swap(arr, prev, prev + 1);
            }
        }
    }

    public static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    public static void printArr(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
    }

    public static int[] randomArray(int len, int maxVal) {
        int arrLen = (int) (Math.random() * len);
        int[] arr = new int[arrLen];

        for (int i = 0; i < arr.length; i++) {
            arr[i] = (int) (Math.random() * maxVal);
        }
        return arr;
    }

    public static void main(String[] args) {
//        int[] arr = {2, 8, 5, 6, 9, 4, 1, 3, 5, 2, 8, 7, 4, 6, 2, 0};
        int[] arr = randomArray(20, 50);
        printArr(arr);
        insertSort2(arr);
        printArr(arr);
    }
}
